package b2.scene.fight
{
	import b2.config.*;
	import b2.net.*;
	import b2.player.*;
	import b2.scene.*;
	import b2.scene.fight.skills.*;
	import b2.scene.guide.*;
	import b2.util.*;
	import b2.widget.*;
	import b2.widget.fight.*;
	
	import com.greensock.TweenLite;
	
	import flash.display.*;
	import flash.events.*;
	import flash.filters.*;
	import flash.geom.Point;
	import flash.text.*;
	import flash.utils.*;
	
	import org.flixel.*;

	public class TankSprite extends FlxSprite
	{
		//坦克大小
		public static const TANK_WIDTH:uint = 45;
		//冰面增加的速度
		public static const ICE_VELOCITY_PLUS:int = 80;
		//坦克炮前方位置
		public static const FRONT_POSX:Array = [TANK_WIDTH / 2, TANK_WIDTH + 20, TANK_WIDTH / 2, -20];  
		public static const FRONT_POSY:Array = [-20, TANK_WIDTH /2, TANK_WIDTH + 20, TANK_WIDTH / 2];
		//本人势力
		public static const SIDE_ME:int = 0;
		//好友玩家
		public static const SIDE_FRIEND:int = 1;
		//无意义势力
		public static const SIDE_NULL:int = -3;
		//电脑势力
		public static const SIDE_COMP:int = -1;
		//电脑势力
		public static const SIDE_BASE:int = -2;
		//平局
		public static const SIDE_DRAW:int = -4;
		//坦克唯一号
		public var tankId:int;
		//坦克类型
		public var tankIndex:int;
		//坦克名称
		public var tankName:String;
		//势力阵营（0, 玩家本人; 1, 其他玩家; -1, 电脑势力; -2, 总部; -3, 无意义; -4, 平局)
		public var side:int;
		//最大生命
		public var healthPoint:int;
		//最大能量
		public var energyPoint:int;
		//攻击
		public var attackPoint:int;
		//暴击率（千分比）
		public var criticalAttackRatio:int;
		//防御
		public var armPoint:int;
		//生命条
		private var healthPointBar:ProgressBar;
		//当前生命
		private var _currentHp:int;
		//当前能量
		private var _currentEp:int;
		//方向
		private var _direction:int;
		//心跳
		private var timer:FlxTimer;
		//移动速度
		private var _moveVelocity:int;
		//特殊区域移动变速
		private var velocityPlus:int;
		//当前所在的格子类型
		private var standTile:int;
		//开炮最快间隔（毫秒）
		public var fireCooldown:int;
		//上次开炮时间（毫秒）
		public var lastFireTime:int;
		//当前状态
		public var tankEffect:TankEffect;
		//坦克跟随标签
		public var tag:Sprite;

		//敌人类型
		public var enemyIndex:int;
		//敌人等级
		public var level:int;
		//BOSS等级
		public var bossLevel:int;
		//技能
		public var skills:Object;
		//特殊子弹
		public var specialBullet:EnemySkillConfig;
		//仇恨对象
		public var hateTankId:int;
		//武器发动预告
		public var showMessageFlag:Boolean;
		//tweenLite标志
		public var tweenLiteFlag:Boolean;
		//是否启用AI
		public var flagAI:Boolean;
		
		public function TankSprite(tankId:int, tankIndex:int, tankName:String, side:int, healthPoint:int, energyPoint:int, attackPoint:int, criticalAttackRatio:int, 
			armPoint:int, moveVelocity:int, fireCooldown:int, enemyIndex:int, level:int, bossLevel:int)
		{
			super();
			this.tankId = tankId;
			this.tankIndex = tankIndex;
			this.tankName = tankName;
			this.side = side;
			this.healthPoint = healthPoint;
			this.energyPoint = energyPoint;
			this._currentHp = healthPoint;
			this._currentEp = energyPoint;
			this.attackPoint = attackPoint;
			this.criticalAttackRatio = criticalAttackRatio;
			this.armPoint = armPoint;
			this.moveVelocity = moveVelocity;
			this.fireCooldown = fireCooldown;
			this.enemyIndex = enemyIndex;
			this.level = level;
			this.bossLevel = bossLevel;
			this.skills = new Object();
			tweenLiteFlag = false;
			flagAI = true;
			
			var campIndex:int = FightScene.getInstance().campIndex
			var fortIndex:int = Config.campFortLink[campIndex];
			if (fortIndex == 0)
			{
				velocityPlus = - moveVelocity * 50 / 100;
			}
			else
			{
				velocityPlus = ICE_VELOCITY_PLUS;
			}
			var tankConfig:TankConfig = Config.objectConfigs[tankIndex];
			var FightImage:Class = ResourceHelper.getInstance().getClassByName(tankConfig.fightImage);
			//初始化
			skills = new Object();
			
			if (side == TankSprite.SIDE_COMP)
			{
				var enemyConfig:EnemyConfig = Config.enemyConfigs[enemyIndex];
				ExternalImage.setData(FightImage, tankConfig.fightImage, 135, 135, enemyConfig.filter);
				//初始化敌方技能
				for (var i:int = 0; i < enemyConfig.skills.length; i++)
				{
					var skillIndex:int = enemyConfig.skills[i].index;
					if (skillIndex != SkillHelper.SPECIAL_BULLET)
					{
						if (skills[skillIndex] != null)
							skills[skillIndex + "_"+ i] = SkillHelper.createSkill(this.tankId, this.side, skillIndex, this.level, enemyConfig.skills[i]);
						else
							skills[skillIndex] = SkillHelper.createSkill(this.tankId, this.side, skillIndex, this.level, enemyConfig.skills[i]);
					}
					else
					{
						specialBullet = enemyConfig.skills[i];
					}
					if (skills[skillIndex] == null)
					{
						if (enemyConfig.skills[i].effectValue != null)
							skills[skillIndex] = enemyConfig.skills[i].effectValue;
						else
							skills[skillIndex] = true;
					}
						
				}
			}
			else if (side == TankSprite.SIDE_ME || side == TankSprite.SIDE_FRIEND)
			{
				ExternalImage.setData(FightImage, tankConfig.fightImage, 135, 135);		
				var tankInfo:TankInfo = PlayerInfoManager.getInstance().tanks[tankId];
				for (i = 0; i < 4; i++)
				{
					var position:int = 6 + i;
					var comIndex:String = tankInfo.getEquipByPosition(position);
					if (comIndex != null)
					{
						var objIndexArr:Array = comIndex.split("_");
						var objectIndex:int = objIndexArr[0];
						var basicLevel:int = objIndexArr[1];
						var strengthenLevel:int = objIndexArr[2];
						var equipConfig:EquipConfig = Config.objectConfigs[objectIndex];
						var quality:int = basicLevel * 5 + strengthenLevel;
						for (var j:int = 0; j < equipConfig.skills.length; j++)
						{
							var skillConfig:EnemySkillConfig = equipConfig.skills[j];
							if (skillConfig.index != SkillHelper.SPECIAL_BULLET)
							{
								skills[equipConfig.position + "_" + j] = SkillHelper.createSkill(tankId, side, skillConfig.index, quality, skillConfig);
							}
							else
							{
								specialBullet = skillConfig;
							}
						}
					}
				}
			}
			else
			{
				ExternalImage.setData(FightImage, tankConfig.fightImage, 135, 135);
			}
			
			loadGraphic(ExternalImage, true, true, TANK_WIDTH, 0, true);
			
			this.width = TANK_WIDTH;
			this.height = TANK_WIDTH;
			
			this.addAnimation("left", [0]);
			this.addAnimation("down", [1]);
			this.addAnimation("up", [2]);
			
			timer = new FlxTimer();
			timer.start(1, 999999, onTick);
			
			//跟随标签
			tag = new Sprite();
			//标签缓存加速
			tag.cacheAsBitmap = true;
			//名字
			var nameText:TextField = new TextField();
			nameText.selectable = false;
        	nameText.autoSize = TextFieldAutoSize.LEFT;
			nameText.defaultTextFormat = new TextFormat("微软雅黑", 12, 0x00AA00);
			if (bossLevel > 0)
				nameText.filters = [new GlowFilter(0xFFFF00, 1, 1.3, 1.3, 100, BitmapFilterQuality.HIGH)];
			else
				nameText.filters = [new GlowFilter(0xFFFFFF, 1, 1.3, 1.3, 100, BitmapFilterQuality.HIGH)];
			var playerState:PlayState = FlxG.state as PlayState;
			//自身势力
			if (side == TankSprite.SIDE_ME)
			{
				nameText.htmlText = "<font color='#00AA00'>" + tankName + "</font>";
			}
			else
			{
				nameText.htmlText = "<font color='#FF0000'>" + tankName + "</font>";
			}
			for (i = 0; i < bossLevel; i++)
			{
				nameText.htmlText += "<font color='#00AA00'>★</font>";
			}
			nameText.x = (this.width - nameText.width) / 2;
			nameText.y = -25;
			tag.addChild(nameText);
			//生命条
			var HealthPointBarFrame:Class = ResourceHelper.getInstance().getClassByName("HealthPointBarFrame");
			var HealthPointBar:Class = ResourceHelper.getInstance().getClassByName("HealthPointBar");
			healthPointBar = new ProgressBar(HealthPointBarFrame, HealthPointBar, 1, 1);
			healthPointBar.x = (this.width - healthPointBar.width) / 2;
			healthPointBar.y = -healthPointBar.height;
			tag.addChild(healthPointBar);
			FightScene.getInstance().effectLayer.addChild(tag);

			//坦克状态效果
			tankEffect = new TankEffect(tankId);
			FightScene.getInstance().effectLayer.addChild(tankEffect);
			
		}
		
		public function set direction(d:int):void
		{
			if (tankEffect.hasEffect(EffectConfig.NIRVANA))
				return;
			_direction = d % 4;
			if (d == 0)
			{
				this.facing = FlxObject.UP;
				this.play("up");
			}
			else if (d == 1)
			{
				this.play("left");
				this.facing = FlxObject.RIGHT;
			}
			else if (d == 2)
			{
				this.facing = FlxObject.DOWN;
				this.play("down");
			}
			else
			{
				this.play("left");
				this.facing = FlxObject.LEFT;
			}
		}
		
		//坦克碰撞
		public function onCollideByTank(tank:TankSprite):void
		{
			var playerState:PlayState = FlxG.state as PlayState;
			tankEffect.addEffect(EffectConfig.COLLIDE, 1, -1, -1, -1);
			if (tank.tankEffect.hasEffect(EffectConfig.BURN))
			{
				var effectValue:int = tank.tankEffect.effects[EffectConfig.BURN][2];
				playerState.updateTankStatus(this.tankId, tank.tankId, this.currentHp, -effectValue, 0, 0);
			}
			if (tankEffect.hasEffect(EffectConfig.NIRVANA))
				playerState.killTank(this.tankId, tank.tankId); 
		}
		
		//子弹碰撞
		public function onCollideByBullet(bullet:BulletSprite):void
		{
			var playerState:PlayState = FlxG.state as PlayState;
			hateTankId = bullet.tankId;
			playerState.explodeBullet(bullet.bulletId, true);
			if (side == TankSprite.SIDE_ME)
				BSound.getInstance().playEffect("SoundDang");
			//排除物理无效或魔法无效
			if (skills[SkillHelper.PHYSICAL_DEFENSE] != null)
			{
				if (bullet.effectIndex <= 0)
					return;
			}
			if (skills[SkillHelper.MAGIC_DEFENSE] != null)
			{
				if (bullet.effectIndex > 0)
					return;
			}
			//闪烁
			if (skills[SkillHelper.BLINK] != null)
			{
				var skill:Blink = skills[SkillHelper.BLINK] as Blink;
				if (skill.checkTime())
				{
					skill.discharge(x, y, direction);
					//不受伤害
					if (!skill.isDamage())
					{
						return;
					}
				}
			}
			//涅槃状态
			if (tankEffect.hasEffect(EffectConfig.NIRVANA))
			{
				playerState.killTank(this.tankId, bullet.tankId);
			}
			//排除无敌状态 和 头盔起作用状态(子弹于坦克方向相反 ，方向相减为2)
			else if (!tankEffect.hasEffect(0) && !(tankEffect.hasEffect(EffectConfig.HELMET) && Math.abs(direction - bullet.direction) == 2))
			{
				var hurt:int = Math.max(1, bullet.attackPoint - armPoint);
				//能量护盾
				if (tankEffect.hasEffect(11) && currentEp > 0)
				{
					//吸收伤害比例
					var absorbPercent:int = tankEffect.effects[11][2];
					var epHurt:int = Math.max(hurt * absorbPercent / 1000, 1);
					var hpHurt:int = hurt - epHurt;
					playerState.updateTankStatus(tankId, bullet.tankId, currentHp, -hpHurt, currentEp, -epHurt, bullet.criticalFlag);
				}
				//荆棘
				else if (tankEffect.hasEffect(17))
				{
					var bulletOwnerTank:TankSprite = playerState.tanks[bullet.tankId];
					if (bulletOwnerTank != null)
					{
						//反弹比例
						var mirrorPercent:int = tankEffect.effects[17][2];
						var mirrorHurt:int = Math.max(hurt * mirrorPercent / 1000, 1);
						hurt = hurt - mirrorHurt;
						playerState.updateTankStatus(bullet.tankId, tankId, bulletOwnerTank.currentHp, -mirrorHurt, 0, 0, bullet.criticalFlag);
					}
					playerState.updateTankStatus(tankId, bullet.tankId, currentHp, -hurt, 0, 0, bullet.criticalFlag);
				}
				else
					playerState.updateTankStatus(tankId, bullet.tankId, currentHp, -hurt, 0, 0, bullet.criticalFlag);
				if (bullet.effectIndex > 0)
				{
					playerState.addTankEffect(tankId, bullet.tankId, bullet.effectIndex, bullet.effectDuration, bullet.effectValue, 0); 
				}
			}
		}
		
		public function get direction():int
		{
			return _direction;
		}
		
		public function move(destX:Number, destY:Number):Boolean
		{
			var playerState:PlayState = FlxG.state as PlayState;
			var newPath:FlxPath;
			var centDestX:Number = destX + PlayState.TILE_WIDTH / 2;
			var centDestY:Number = destY + PlayState.TILE_WIDTH / 2;
//			if (path == null || path.nodes.length == 0 || path.tail().x != centDestX || path.tail().y != centDestY)
			{
				newPath = findPath(this.x, this.y, destX, destY);
				if (newPath != null)
				{
					stopFollowingPath(true);
					followPath(newPath, moveVelocity);
					return true;
				}
			}
			return false;
		}
		
		private function findPath(startX:int, startY:int, endX:int, endY:int):FlxPath
		{
			var playerState:PlayState = FlxG.state as PlayState;
			var distances:Array = playerState.distances.concat();
			var tileMap:FlxTilemap = playerState.tileMap;
			var stepWidth:int = PlayState.STEP_WIDTH;
			var widthInSteps:int = PlayState.STEP_NUM;
			
			//初始化距离数组
			var parent:Object = new Object(); 
			//左上角的格点
			var currentIndex:int = playerState.posToGridIndex(startX, startY);
			distances[currentIndex] = 0;
			var neighbors:Array = [currentIndex];
			//检查边缘
			var left:Boolean;
			var up:Boolean;
			var right:Boolean;
			var down:Boolean;
			var index:int;
			var current:Array;
			var foundEnd:Boolean = false;
			var destIndex:int = playerState.posToGridIndex(endX, endY);;
			//开始广度探索
			while (neighbors.length > 0 && !foundEnd)
			{
				current = neighbors;
				neighbors = new Array();
				
				for (var i:int = 0; i < current.length; i++)
				{
					currentIndex = current[i];
					if (currentIndex == destIndex)
					{
						foundEnd = true;
						break;
					}
					//边缘检查
					left = currentIndex % widthInSteps > 0;
					right = currentIndex % widthInSteps < widthInSteps - 1;
					up = currentIndex / widthInSteps > 0;
					down = currentIndex / widthInSteps < widthInSteps - 1;
					//上方
					if (up)
					{
						index = currentIndex - widthInSteps;
						if (distances[index] > 0 && distances[currentIndex] + stepWidth < distances[index])
						{
							distances[index] = distances[currentIndex] + stepWidth;
							neighbors.push(index);
							parent[index] = currentIndex;
						}
					}
					//右方
					if (right)
					{
						index = currentIndex + 1;
						if (distances[index] > 0 && distances[currentIndex] + stepWidth < distances[index])
						{
							distances[index] = distances[currentIndex] + stepWidth;
							neighbors.push(index);
							parent[index] = currentIndex;
						}
					}
					//下方
					if (down)
					{
						index = currentIndex + widthInSteps;
						if (distances[index] > 0 && distances[currentIndex] + stepWidth < distances[index])
						{
							distances[index] = distances[currentIndex] + stepWidth;
							neighbors.push(index);
							parent[index] = currentIndex;
						}
					}
					//左方
					if (left)
					{
						index = currentIndex - 1;
						if (distances[index] > 0 && distances[currentIndex] + stepWidth < distances[index])
						{
							distances[index] = distances[currentIndex] + stepWidth;
							neighbors.push(index);
							parent[index] = currentIndex;
						}
					}
				}
			}
			if (!foundEnd)
				return null;
			//回溯找到最短路径
			var points:Array = new Array();
			currentIndex = destIndex;
			points.push(new FlxPoint(tileMap.x + uint(currentIndex % widthInSteps) * stepWidth + stepWidth * 1.5, 
				tileMap.y + uint(currentIndex / widthInSteps) * stepWidth + stepWidth * 1.5));
			while (parent[currentIndex] != null)
			{
				currentIndex = parent[currentIndex];
				points.push(new FlxPoint(tileMap.x + uint(currentIndex % widthInSteps) * stepWidth + stepWidth * 1.5, 
					tileMap.y + uint(currentIndex / widthInSteps) * stepWidth + stepWidth * 1.5));
			}
			//优化节点
			if (points.length > 1)
			{
				var p0:FlxPoint = points[points.length - 1];
				var p1:FlxPoint = new FlxPoint(startX + stepWidth * 1.5, startY + stepWidth * 1.5); 
				var p2:FlxPoint = points[points.length - 2];
				if (p0.x == p1.x && p1.x == p2.x && (p0.y - p1.y) * (p2.y - p1.y) < 0
					|| p0.y == p1.y && p1.y == p2.y && (p0.x - p1.x) * (p2.x - p1.x) < 0)
					points.pop();
			}
			return new FlxPath(points.reverse());
		}
		
		override public function update():void
		{
			//调整方向
			var threshold:Number = 1;
			if (this.velocity.y < -threshold)
				this.direction = 0;
			else if (this.velocity.x > threshold)
				this.direction = 1;
			else if (this.velocity.y > threshold)
				this.direction = 2;
			else if (this.velocity.x < -threshold)
				this.direction = 3;
			//坦克生命值槽跟随
			tag.x = this.x;
			tag.y = this.y;
			tag.alpha = this._alpha;
			
			//坦克状态效果跟随
			tankEffect.followTank(this.x, this.y, this.direction);

			if (this.pathSpeed == 0)
			{
				this.velocity.x = 0;
				this.velocity.y = 0;
			}
			
			var tileX:int = (this.x + TANK_WIDTH / 2 - PlayState.OFFSET_X) / PlayState.TILE_WIDTH;
			var tileY:int = (this.y + TANK_WIDTH / 2 - PlayState.OFFSET_Y) / PlayState.TILE_WIDTH;
			if (tileX == 4 && tileY == 4 && GuideScene.getInstance().step == 6)
				GuideScene.getInstance().step++;
			else if (tileX == 9 && tileY == 4 && GuideScene.getInstance().step == 7)
				GuideScene.getInstance().step++;
			else if (tileX == 5 && tileY == 8 && GuideScene.getInstance().step == 8)
				GuideScene.getInstance().step++;
			var playerState:PlayState = FlxG.state as PlayState;
			//冰块速度效果
			var currentStandTile:int = playerState.tileMap.getTile(tileX, tileY);
			
			if (standTile != currentStandTile)
			{ 
				if (currentStandTile == 4)
				{
					moveVelocity += velocityPlus;
				}
				else if (standTile == 4)
				{
					moveVelocity -= velocityPlus;
				}
				//如果有草丛隐身技能
				if (this.skills[SkillHelper.JUNGLE_INVISIBLE] != null)
				{
					if (currentStandTile == 5)
					{
						TweenLite.to(this, 0.5, {alpha:0});
					}
					else if (standTile == 5)
					{
						TweenLite.to(this, 0.5, {alpha:1});
					}
				}
			}
			standTile = currentStandTile;
			
			var me:PlayerInfo = PlayerInfoManager.getInstance().players[PlayerInfoManager.getInstance().myUserId];
			//疯狂状态 
			if (this.tankId == me.campTankId && tankEffect.hasEffect(16))
			{
				if (this.pathSpeed == 0)
				{
					var randPos:Point = (FlxG.state as PlayState).getRandEmptyPos();
					move(PlayState.OFFSET_X + PlayState.TILE_WIDTH * randPos.x, PlayState.OFFSET_Y + PlayState.TILE_WIDTH * randPos.y);
				}
			}

			if (flagAI)
			{
				//自己坦克
				var state:PlayState = FlxG.state as PlayState;
				if (this.tankId == state.myTankId)
				{
					startMyAI();
				}
				//电脑坦克
				else if (side == SIDE_COMP)
				{
					startCompAI();
				}
				//好友坦克
				else if (side == SIDE_FRIEND)
				{
					startFriendAI();
				}
			}
		}
		
		private function getHateTankDirection():int
		{
			var state:PlayState = FlxG.state as PlayState;
			var hateTank:TankSprite = state.tanks[this.hateTankId]; 
			var diffX:Number = hateTank.x - this.x;
			var diffY:Number = hateTank.y - this.y;
			var direction:int;
			if (Math.abs(diffY) > Math.abs(diffX) && diffY < 0)
				direction = 0;
			else if (Math.abs(diffX) > Math.abs(diffY) && diffX > 0)
				direction = 1;
			else if (Math.abs(diffY) > Math.abs(diffX) && diffY >= 0)
				direction = 2;
			else
				direction = 3;
			return direction;
		}

		//自身坦克智能
		private function startMyAI():void
		{
			var state:PlayState = FlxG.state as PlayState;
			//自动开炮
			var skillArea:SkillArea = new SkillArea(x + + PlayState.TILE_WIDTH / 2, y + PlayState.TILE_WIDTH / 2, direction);
			skillArea.addArea(PlayState.TILE_WIDTH * 13, 0, PlayState.TILE_WIDTH / 2, PlayState.TILE_WIDTH / 2);
			for (var tankIdStr:String in state.tanks)
			{
				var tank:TankSprite = state.tanks[tankIdStr];
				if ((tank.side == SIDE_COMP || tank.side == SIDE_FRIEND) && 
					(skillArea.contain(tank.x + 2, tank.y + 2) || skillArea.contain(tank.x + PlayState.TILE_WIDTH - 2, tank.y + PlayState.TILE_WIDTH - 2)))
				{
					var fireTime:int = getTimer();
					if (fireTime - lastFireTime >= fireCooldown)
					{
						fireBullet(0, 0, -1, -1, -1, direction);
						break;
					}
				}
			}
		}
		
		private function startFriendAI():void
		{
			//时间停止
			if (tankEffect.hasEffect(10))
				return;
			var state:PlayState = FlxG.state as PlayState;
			startBossAI();
			//坦克移动
			if (!tankEffect.hasEffect(EffectConfig.MOVE_STOP) && !tweenLiteFlag)
			{
				//继续移动
				if (this.pathSpeed == 0)
				{
					var randPos:Point = state.getRandEmptyPos();
					move(PlayState.OFFSET_X + PlayState.TILE_WIDTH * randPos.x, PlayState.OFFSET_Y + PlayState.TILE_WIDTH * randPos.y);
				}
			}
			var fireTime:int = getTimer();
			if (fireTime - lastFireTime >= fireCooldown)
			{
				if (Math.random() < 0.9)
				{
					//主动攻击武器
					var bulletIndex:int = 0;
					var bulletApPlus:int = 0;
					var effectIndex:int = -1;
					var effectValue:int = -1;
					var effectDuration:int = -1;
					if (specialBullet != null)
					{
						bulletIndex = specialBullet.bulletIndex;
						effectIndex = specialBullet.effectIndex;
						bulletApPlus = level < specialBullet.bulletApPlus.length ? specialBullet.bulletApPlus[level] : specialBullet.bulletApPlus[0] * level;
						effectValue = level < specialBullet.effectValue.length ? specialBullet.effectValue[level] : specialBullet.effectValue[0] * level;
						effectDuration = level < specialBullet.effectDuration.length ? specialBullet.effectDuration[level] : specialBullet.effectDuration[0];
					}
					fireBullet(bulletIndex, bulletApPlus, effectIndex, effectValue, effectDuration, direction);
				}
			}
			var skill:BasicSkill;
			for (var skillStr:String in skills)
			{
				if (!(skills[skillStr] is BasicSkill))
					continue;
				skill = skills[skillStr] as BasicSkill;
				if (skill.checkSkillTriggerPremise(this.x + PlayState.TILE_WIDTH / 2, this.y + PlayState.TILE_WIDTH / 2, direction))
				{
					//释放技能
					skill.discharge(this.x + PlayState.TILE_WIDTH / 2, this.y + PlayState.TILE_WIDTH / 2, direction);
				}
			}
		}
		
		private function startBossAI():void
		{
			var state:PlayState = FlxG.state as PlayState;
			//仇恨
			var hateTank:TankSprite = state.tanks[this.hateTankId]; 
			if (hateTank != null)
			{
				var distX:Number = Math.abs(this.x - hateTank.x);
				var distY:Number = Math.abs(this.y - hateTank.y);
				if (distX > PlayState.TILE_WIDTH || distY > PlayState.TILE_WIDTH)
				{
					if (distX < PlayState.TILE_WIDTH * 4 && distY < PlayState.TILE_WIDTH * 4)
					{
						if (path == null || path.nodes.length == 0 || (Math.abs(path.tail().x - hateTank.x) > PlayState.TILE_WIDTH || 
							Math.abs(path.tail().y - hateTank.y) > PlayState.TILE_WIDTH))
						{
							move(hateTank.x, hateTank.y);	
						}
					}
				}
				else
				{
					if (pathSpeed == 0)
						direction = getHateTankDirection();
				}
			}
		}
		
		private function startCompAI():void
		{
			//时间停止
			if (tankEffect.hasEffect(10))
				return;
			var enemyConfig:EnemyConfig = Config.enemyConfigs[this.enemyIndex];
			if (this.bossLevel > 0)
				startBossAI();
			var state:PlayState = FlxG.state as PlayState;
			//坦克移动
			if (!enemyConfig.noMove && !tankEffect.hasEffect(EffectConfig.MOVE_STOP) && !tweenLiteFlag)
			{
				//继续移动
				if (this.pathSpeed == 0)
				{
					var randPos:Point = state.getRandEmptyPos();
					move(PlayState.OFFSET_X + PlayState.TILE_WIDTH * randPos.x, PlayState.OFFSET_Y + PlayState.TILE_WIDTH * randPos.y);
				}
			}
			
			if (!enemyConfig.noFire)
			{
				var fireTime:int = getTimer();
				if (fireTime - lastFireTime >= fireCooldown)
				{
					if (Math.random() < 0.9)
					{
						//主动攻击武器
						var bulletIndex:int = 0;
						var bulletApPlus:int = 0;
						var effectIndex:int = -1;
						var effectValue:int = -1;
						var effectDuration:int = -1;
						if (specialBullet != null)
						{
							bulletIndex = specialBullet.bulletIndex;
							effectIndex = specialBullet.effectIndex;
							bulletApPlus = level < specialBullet.bulletApPlus.length ? specialBullet.bulletApPlus[level] : specialBullet.bulletApPlus[0] * level;
							effectValue = level < specialBullet.effectValue.length ? specialBullet.effectValue[level] : specialBullet.effectValue[0] * level;
							effectDuration = level < specialBullet.effectDuration.length ? specialBullet.effectDuration[level] : specialBullet.effectDuration[0];
						}
						fireBullet(bulletIndex, bulletApPlus, effectIndex, effectValue, effectDuration, direction);
						if (Math.random() < 0.3)
						{
							//二尾
							if (enemyIndex == 224)
							{
								//后
								fireBullet(bulletIndex, bulletApPlus, effectIndex, effectValue, effectDuration, (direction + 2) % 4);
							}
							//225, 三尾; 274, 修罗道 
							else if (enemyIndex == 225 || enemyIndex == 274)
							{
								//左
								fireBullet(bulletIndex, bulletApPlus, effectIndex, effectValue, effectDuration, (direction + 1) % 4);
								//右
								fireBullet(bulletIndex, bulletApPlus, effectIndex, effectValue, effectDuration, (direction + 3) % 4);
							}
							//226, 四尾; 222, 九尾狐
							else if (enemyIndex == 226 || enemyIndex == 222)
							{
								//左
								fireBullet(bulletIndex, bulletApPlus, effectIndex, effectValue, effectDuration, (direction + 1) % 4);
								//右
								fireBullet(bulletIndex, bulletApPlus, effectIndex, effectValue, effectDuration, (direction + 3) % 4);
								//后
								fireBullet(bulletIndex, bulletApPlus, effectIndex, effectValue, effectDuration, (direction + 2) % 4);
							}
						}
					}
					else
						lastFireTime = fireTime;
				}
			}
			var skill:BasicSkill;
			for (var skillStr:String in skills)
			{
				if (!(skills[skillStr] is BasicSkill))
					continue;
				skill = skills[skillStr] as BasicSkill;
				if (skill.checkSkillTriggerPremise(this.x + PlayState.TILE_WIDTH / 2, this.y + PlayState.TILE_WIDTH / 2, direction))
				{
					//释放技能
					skill.discharge(this.x + PlayState.TILE_WIDTH / 2, this.y + PlayState.TILE_WIDTH / 2, direction);
				}
			}
		}
				
		private function onTick(timer:FlxTimer):void
		{
			tankEffect.onTick(timer);
			for (var index:String in skills)
			{
				if (skills[index] is BasicSkill)
				{
					var skill:BasicSkill = skills[index];
					skill.onTimer();
				}
			}
		}
		
		public function startFinalWeapon(movieIndex:int, range:int, damage:int, effectIndex:int, effectDuration:int, effectValue:int):void
		{
			var playerState:PlayState = FlxG.state as PlayState;
			var posX:int = this.x + TANK_WIDTH / 2;
			var posY:int = this.y + TANK_WIDTH / 2;
			playerState.playFixMovie(movieIndex, posX, posY, 0, true);
			TweenLite.delayedCall(1.5, finalWeaponOnHit, [posX, posY, range, damage, effectIndex, effectDuration, effectValue]);
		}
		
		private function finalWeaponOnHit(posX:int, posY:int, range:int, damage:int, effectIndex:int, effectDuration:int,
			effectValue:int):void
		{
			var playerState:PlayState = FlxG.state as PlayState;
			for (var tankIdStr:String in playerState.tanks)
			{
				var tank:TankSprite = playerState.tanks[tankIdStr];
				if (tank != null && tank.side != -2 && this.side != tank.side)
				{
					if (Math.abs(posX - tank.x) < PlayState.TILE_WIDTH * range && Math.abs(posY - tank.y) < PlayState.TILE_WIDTH * range)
					{  
						playerState.updateTankStatus(tank.tankId, this.tankId, tank.currentHp, -damage, 0, 0, true);
						playerState.addTankEffect(tank.tankId, this.tankId, effectIndex, effectDuration, effectValue, 0);
					}
				}
			}
		}
		
		public function fireBullet(bulletIndex:int = 0, bulletApPlus:int = 0, effectIndex:int = -1, effectValue:int = -1, effectDuration:int = -1, fireDirection:int = 0):void
		{
			if (tankEffect.hasEffect(EffectConfig.NIRVANA))
				return;
			var state:PlayState = FlxG.state as PlayState;
			
			var posX:Number = this.x + TANK_WIDTH / 2 - BulletSprite.BULLET_WIDTH / 2; 
			var posY:Number = this.y + TANK_WIDTH / 2 - BulletSprite.BULLET_WIDTH / 2;
			var vX:Number;
			var vY:Number;
			if (fireDirection == 0)
			{
				vX = 0;
				vY = -BulletSprite.BULLET_VELOCITY;  
			}
			else if (fireDirection == 1)
			{
				vX = BulletSprite.BULLET_VELOCITY;
				vY = 0;
			}
			else if (fireDirection == 2)
			{
				vX = 0;
				vY = BulletSprite.BULLET_VELOCITY;
			}
			else
			{
				vX = -BulletSprite.BULLET_VELOCITY;
				vY = 0;
			}
			var bulletId:int = int.MAX_VALUE * Math.random();
			//普通攻击
			var bulletAp:int = this.attackPoint;
			var criticalFlag:Boolean = false;
			//暴击
			if (Math.random() < this.criticalAttackRatio / 1000)
			{
				bulletAp *= 2;
				criticalFlag = true;
			}
			//上下浮动10%
			bulletAp += (Math.random() - 0.5) * this.attackPoint * 0.2;
			//额外伤害
			bulletAp += bulletApPlus;
			state.createBullet(bulletId, bulletIndex, tankId, side, bulletAp, fireDirection, posX, posY, vX, vY, criticalFlag, effectIndex, 
				effectValue, effectDuration);
			if (side == TankSprite.SIDE_ME)
				BSound.getInstance().playEffect("SoundFire");
			lastFireTime = getTimer();    
		}
		
		public override function kill():void
		{
			super.kill();
			//坦克爆炸
			var BulletExplode:Class = ResourceHelper.getInstance().getClassByName("BulletExplode");
			var explodeMc:BasicMc = new BasicMc(BulletExplode, 40, false, true);
			explodeMc.width = 25;
			explodeMc.scaleY = explodeMc.scaleX;
			explodeMc.x = this.x + TANK_WIDTH / 2;
			explodeMc.y = this.y + TANK_WIDTH / 2;
			SceneManager.getInstance().currentScene.addChild(explodeMc);
			BSound.getInstance().playEffect("SoundExplode");
			
			if (GuideScene.getInstance().step == 9)
				GuideScene.getInstance().step++;
			var state:PlayState = FlxG.state as PlayState;
			
			//电脑坦克，我是宿主
			var campIndex:int = FightScene.getInstance().campIndex;
			var fortIndex:int = Config.campFortLink[campIndex];
			var campConfig:CampConfig = Config.campConfigs[campIndex];
			var fortressConfig:FortressConfig = Config.fortressConfigs[fortIndex];
			if (this.side == SIDE_COMP)
			{
				//掉落消耗性物品
				var enemyConfig:EnemyConfig = Config.enemyConfigs[this.enemyIndex];
				if (enemyConfig.dropItem != null)
				{
					var itemPossibility:Number = 0;
					var rand:Number = Math.random();
					for (var i:int = 0; i < enemyConfig.dropItem.length; i++)
					{ 
						var dropItemStrs:Array = enemyConfig.dropItem[i].split(",");
						//英雄模式减少道具掉落
						if (state.isHeroMode)
						{
							itemPossibility += Math.max(0, parseInt(dropItemStrs[1]) - (parseInt(dropItemStrs[1]) * fortressConfig.heroMode.dropPossibilityDecrease));
						}
						else
						{
							itemPossibility += parseInt(dropItemStrs[1]);
						}
						if (rand < itemPossibility / 1000)
						{
							var itemIndex:int = dropItemStrs[0];
							var randPosX:int = PlayState.OFFSET_X + (PlayState.TILE_NUM - 1) * PlayState.TILE_WIDTH * Math.random();
							var randPosY:int = PlayState.OFFSET_Y + (PlayState.TILE_NUM - 1) * PlayState.TILE_WIDTH * Math.random();
							state.createDropItem(int.MAX_VALUE * Math.random(), itemIndex, side, this.x, this.y, randPosX, randPosY, -1, -1, -1, -1, true);
							break; 
						}
					}
				}
				//掉落宝箱
				itemPossibility = 0;
				rand = Math.random();
				for (i = 0; i < campConfig.awards.length; i++)
				{
					
					var awardConfig:CampAwardConfig = campConfig.awards[i];
					
					var actualBossLevel:int = (bossLevel > 0 && state.isHeroMode) ? bossLevel - fortressConfig.heroMode.enemyBossLevelIncrease : bossLevel;
					if (awardConfig.bossLevel == actualBossLevel)
					{
						var objectConfig:CommonObjConfig = Config.objectConfigs[awardConfig.objectIndex];
						var awardPossibility:int = awardConfig.possibility;
						if (state.isHeroMode && objectConfig.noBasicLevel)
						{
								awardPossibility += awardPossibility * fortressConfig.heroMode.prizePossibilityIncrease / 100;
						}
						itemPossibility += awardPossibility;
						//掉落奖励宝箱
						if (rand < itemPossibility / 1000 || GuideScene.getInstance().step == 10)
						{
							if (GuideScene.getInstance().enabled)
							{
								randPosX = 300;
								randPosY = 300;
							}
							else
							{
								randPosX = PlayState.OFFSET_X + (PlayState.TILE_NUM - 1) * PlayState.TILE_WIDTH * Math.random();
								randPosY = PlayState.OFFSET_Y + (PlayState.TILE_NUM - 1) * PlayState.TILE_WIDTH * Math.random();
							}
							
							var basicLevel:int = awardConfig.basicLevel;
							var strengthenLevel:int = awardConfig.strengthenLevel;
							//英雄模式奖励
							if (state.isHeroMode)
							{
								if (!objectConfig.noBasicLevel)
								{
									if (!objectConfig.noStrengthenLevel)
									{
										strengthenLevel = (awardConfig.strengthenLevel + fortressConfig.heroMode.equipLevelIncrease) % 5;
										basicLevel = (awardConfig.basicLevel + (awardConfig.strengthenLevel + fortressConfig.heroMode.equipLevelIncrease) / 5) % 5;
									}
									else
									{
										basicLevel = (awardConfig.basicLevel + fortressConfig.heroMode.medalLevelIncrease) % 5;
									}
								}
							}
							var boxIndex:int;
							//石油，天然气  破木箱
							if (awardConfig.objectIndex == CommonObjConfig.EXP)
								boxIndex = DropItemConfig.EXP_BOX;
							else if (awardConfig.objectIndex == CommonObjConfig.OIL)
								boxIndex = DropItemConfig.OIL_BOX;
							//勋章 铜箱
							else if (awardConfig.objectIndex == 5 || awardConfig.objectIndex == 6 || awardConfig.objectIndex == 7 || awardConfig.objectIndex == 8)
								boxIndex = DropItemConfig.COPPER_BOX;
							//荣誉 银箱
							else if (awardConfig.objectIndex == 3)
								boxIndex = DropItemConfig.HONOUR;
							//英雄之证
							else if (awardConfig.objectIndex == 11)
								boxIndex = DropItemConfig.HERO_VERT;
							//装备 金箱
							else 
								boxIndex = DropItemConfig.GOLD_BOX;
							state.createDropItem(int.MAX_VALUE * Math.random(), boxIndex, side, this.x, this.y, randPosX, randPosY, awardConfig.objectIndex, 
								basicLevel, strengthenLevel, awardConfig.objectNum, true);
							break;
						}
					}
				}
			}
		} 
		
		public override function destroy():void
		{
			super.destroy();
			timer.destroy();
			if (tag != null && tag.parent != null)
			{
				tag.parent.removeChild(tag);
				tag = null;
			}
			if (tankEffect != null)
			{
				if (tankEffect.parent != null)
					tankEffect.parent.removeChild(tankEffect);
				tankEffect.destroy();
				tankEffect = new TankEffect(this.tankId);
			}
		}
		
		public function get currentHp():int
		{
			return _currentHp;
		} 
		
		public function set currentHp(newHp:int):void
		{
			_currentHp = Math.min(Math.max(0, newHp), this.healthPoint);
			healthPointBar.percentage = _currentHp / healthPoint;
		}

		public function get currentEp():int
		{
			return _currentEp;
		} 
		
		public function set currentEp(newEp:int):void
		{
			_currentEp = Math.min(Math.max(0, newEp), this.energyPoint);
		}
		
		public function set moveVelocity(mv:int):void
		{
			_moveVelocity = mv;
			if (pathSpeed > 0)
				pathSpeed = mv;
		}
		
		public function get moveVelocity():int
		{
			return _moveVelocity;
		}
	}
}